package com.video_study.service.serviceImpl;

import cn.dsna.util.images.ValidateCode;
import com.video_study.dao.UsersMapper;
import com.video_study.pojo.Users;
import com.video_study.result.ExceptionMsg;
import com.video_study.result.ResponseData;
import com.video_study.service.LoginService;
import com.video_study.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UsersMapper usersMapper;

    @Override
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        ValidateCode validateCode = new ValidateCode(160,40,4,30);
        String code = validateCode.getCode();
        request.getSession().setAttribute("code",code);
        try {
            validateCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ResponseData login(HttpServletRequest request, String username, String password, String code) {
      String code1 =   (String) request.getSession().getAttribute("code");
      if(code1.equalsIgnoreCase(code.trim())){
          //判断用户信息  用户名
         Users user =  usersMapper.selectByUsername(username);
          if(user!=null&&user.getPassword().equalsIgnoreCase(Md5Util.getMd5(username,password))){
              request.getSession().setAttribute("user",user);
              return new ResponseData(ExceptionMsg.SUCCESS,user);
          }else{
              return new ResponseData("000407","用户名或者密码错误",null);
          }
      }else{
          return new ResponseData("000406","验证码错误",null);
      }






    }
}
